package org.jeecg.modules.demo.com.kunpeng.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.demo.com.kunpeng.entity.CollectionRecord;
import org.jeecg.modules.demo.com.kunpeng.entity.OaProject;
import org.jeecg.modules.demo.com.kunpeng.entity.dto.OaProjectQueryDTO;
import org.jeecg.modules.demo.com.kunpeng.ex.ServiceCode;
import org.jeecg.modules.demo.com.kunpeng.ex.ServiceException;
import org.jeecg.modules.demo.com.kunpeng.mapper.CollectionRecordMapper;
import org.jeecg.modules.demo.com.kunpeng.mapper.OaAdminMapper;
import org.jeecg.modules.demo.com.kunpeng.mapper.OaProjectMapper;
import org.jeecg.modules.demo.com.kunpeng.service.IOaProjectService;
import org.jeecg.modules.demo.com.kunpeng.vo.CollectionRecordVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

@Service
@Slf4j
public class OaProjectServiceImpl extends ServiceImpl<OaProjectMapper, OaProject> implements IOaProjectService {

    //项目前缀
    private static Integer PROJECT_SUFFIX;

    @Autowired
    private OaProjectMapper oaProjectMapper;

    @Autowired
    private OaAdminMapper oaAdminMapper;

    @Autowired
    private CollectionRecordMapper collectionRecordMapper;
    /**
     * 根据项目名称获取项目详情
     * @param name
     * @return
     */
    @Override
    public OaProject selectOaProjectByName(String name) {
        OaProject oaProject = oaProjectMapper.selectOaProjectByName(name);
        if(oaProject==null){
            String message="该项目不存在，请联系管理员！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        return oaProject;
    }


    /**
     * 获取项目名称列表
     * @return
     */
    @Override
    public List<String> listProjectName() {
        List<String> projectNameList = oaProjectMapper.listProjectName();
        return projectNameList;
    }

    /**
     * 根据项目名称查询项目列表
     * @param page
     * @param oaProjectQueryDTO
     * @return
     */
    @Override
    public Page<OaProject> projectList(Page<OaProject> page, OaProjectQueryDTO oaProjectQueryDTO) {
        Page<OaProject> oaProjectListPage = page.setRecords(oaProjectMapper.projectList(page, oaProjectQueryDTO.getName()));

        if(oaProjectListPage.getSize()==0){
            String message="没有符合条件的数据，请重新输入！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        //给项目回款状态赋值
        for(OaProject oaProject:oaProjectListPage.getRecords()){
            //回款状态
            if(oaProject.getAlreadyReturnMoney().compareTo(BigDecimal.ZERO)==0){
                /*log.info("项目【"+oaProject.getName()+"】回款状态为0");*/
                oaProjectMapper.updateOaProjectReturnMoneyStatus(oaProject.getId(),"0");
                oaProject.setReturnMoneyStatus("0");
            }else {
                if (null != oaProject.getAlreadyReturnMoney() && oaProject.getAlreadyReturnMoney().compareTo(oaProject.getReturnMoney()) < 0) {
                    /*log.info("项目【" + oaProject.getName() + "】回款状态为1");*/
                    oaProjectMapper.updateOaProjectReturnMoneyStatus(oaProject.getId(), "1");
                    oaProject.setReturnMoneyStatus("1");
                } else if (null != oaProject.getAlreadyReturnMoney() && oaProject.getAlreadyReturnMoney().compareTo(oaProject.getReturnMoney()) == 0) {
                    /*log.info("项目【" + oaProject.getName() + "】回款状态为2");*/
                    oaProjectMapper.updateOaProjectReturnMoneyStatus(oaProject.getId(), "2");
                    oaProject.setReturnMoneyStatus("2");
                }
            }
        }
        return oaProjectListPage;
    }


    /**
     * 根据项目编号前缀获取项目列表
     * @param prefix
     * @return
     */
    @Override
    public Integer listOaProjectIdByPrefix(String prefix) {
        List<OaProject> oaProjects = oaProjectMapper.listOaProjectIdByPrefix(prefix);
        /*for (OaProject oaProject:oaProjects) {
            System.out.println("根据前缀查询到的项目数据："+oaProject.toString());
        }*/
        if(oaProjects.size()>0){
            OaProject oaProject = oaProjects.get(oaProjects.size() - 1);
            String projectId = oaProject.getProjectId();
            String substring = projectId.substring(10, 13);
            PROJECT_SUFFIX = Integer.parseInt(substring)+1;
        }else {
            PROJECT_SUFFIX=1;
        }
        return PROJECT_SUFFIX;
    }


    /**
     * 根据id修改项目已回款金额
     * @param collectionRecordVO
     */
    @Override
    public void updateOaProjectAlreadyReturnMoney(CollectionRecordVO collectionRecordVO) {
        BigDecimal collectionAmount = collectionRecordVO.getCollectionAmount();
        System.out.println("回款对象："+collectionRecordVO.toString());
        //根据id查询项目
        OaProject oaProject=oaProjectMapper.selectOaProjectById(collectionRecordVO.getOid());
        /*System.out.println("***************回款时间："+collectionRecordVO.getCollectionTime());*/
        //查询项目的当前已回款金额
        BigDecimal alrReturnMoney = oaProject.getAlreadyReturnMoney();
        log.info("该项目当前已回款金额:"+collectionRecordVO.getCollectionAmount());
        //判断当前已回款金额加上新的金额是否超过项目金额，超过报异常
        alrReturnMoney=alrReturnMoney.add(collectionAmount);
        log.info("当前回款和新金额相加:"+alrReturnMoney);
        if(alrReturnMoney.compareTo(oaProject.getReturnMoney())==1){
            String message="已回款金额超出项目金额，请重新输入！";
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        //不超过，修改数据库的已回款金额值
        BigDecimal newAlreadyReturnMoney = oaProject.getAlreadyReturnMoney().add(collectionRecordVO.getCollectionAmount());
        oaProjectMapper.updateOaProjectAlreadyReturnMoney(collectionRecordVO.getOid(),newAlreadyReturnMoney);

        //修改项目表的fileID
        String fileId = oaProject.getFileId();
        if(null==fileId){
            fileId="";
        }
        String[] str1 = fileId.split(",");

        //收款记录新增文件id
        String fileIds = collectionRecordVO.getFileId();
        String[] str2 = fileIds.split(",");

        //更新项目关联的文件id字符串
        for(int i=0;i<str2.length;i++){
            boolean isContain=false;
            for(int j=0;j<str1.length;j++){
                if(str1[j].equals(str2[i])){
                    isContain=true;
                }
            }
            if(isContain==false){
                if(fileId.equals("")){
                    fileId=str2[i];
                }else {
                    if(!str2[i].equals("")) {
                        fileId = fileId + "," + str2[i];
                    }
                }
            }
        }
        oaProjectMapper.updateOaProjectFileIdById(oaProject.getId(),fileId);

        //修改完项目表再存入收款记录表
        //创建回款记录表对象并赋值
        CollectionRecord collectionRecord=new CollectionRecord();
        BeanUtils.copyProperties(collectionRecordVO,collectionRecord);

        //转换时间格式
        String collectionTime = collectionRecordVO.getCollectionTime();
        SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
        try {
            Long returnTime=sf.parse(collectionTime).getTime()/1000;
            collectionRecord.setCollectionTime(returnTime.intValue());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        collectionRecord.setPayee(collectionRecord.getPayee());
        //获取当前系统时间
        /*Long currentTime = System.currentTimeMillis();
        currentTime/=1000L;
        collectionRecord.setCollectionTime(currentTime.intValue());*/
        //调用方法插入
        int num = collectionRecordMapper.insert(collectionRecord);
        if(num!=1){
            String message="收款记录表数据插入失败，请联系管理员！";
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }

    }


    /**
     * 根据关联客户id获取项目列表
     * @param customerId
     * @return
     */
    @Override
    public List<OaProject> oaProjectListByCustomerId(Integer customerId) {
        List<OaProject> oaProjects = oaProjectMapper.oaProjectListByCustomerId(customerId);
        return oaProjects;
    }
}
